import BaseInput from "@/components/base/Input"
import styled from "@emotion/styled"
import { CSSProperties, createRef, memo, useRef } from "react"
import { Control, FieldPath, FieldValues, UseControllerProps, useController } from "react-hook-form"
import Svg from "../base/Svg"

// 组件Props类型
interface NameInputProps<T extends FieldValues> extends UseControllerProps<T> {
    control: Control<T>
    fieldName: FieldPath<T>
    style?: CSSProperties
    className?: string
}

type NameFields = {
    firstName: string
    middleName?: string
    lastName: string
}

const InputName = memo(
    <T extends FieldValues>({ control, fieldName, className = "", style }: NameInputProps<T>) => {
        // 定义输入框引用数组

        const inputsRef = useRef<Array<React.RefObject<HTMLInputElement>>>(
            // @ts-ignore
            Array(3)
                .fill(null)
                .map(() => createRef()),
        )
        // 字段键名数组
        const fieldKeys = ["firstName", "middleName", "lastName"] as const

        // 使用Controller管理表单状态
        const {
            field: { value, onChange },
            fieldState: { error },
        } = useController<T>({
            name: fieldName,
            control,
            defaultValue: {
                firstName: "",
                middleName: "",
                lastName: "",
            } as never,
            rules: {
                validate: (value) => {
                    if (!value.firstName?.trim()) return "First name is required"
                    if (!value.lastName?.trim()) return "Last name is required"
                    return true
                },
            },
        })

        // 处理输入变化
        const handleChange = (field: (typeof fieldKeys)[number], newValue: string) => {
            const newValues = {
                ...(value as NameFields),
                [field]: newValue,
            }
            onChange(newValues)
        }

        // 处理键盘事件
        const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>, fieldIndex: number) => {
            if (
                (e.key === "Backspace" || e.key === "Delete") &&
                !(value as NameFields)[fieldKeys[fieldIndex]]
            ) {
                e.preventDefault()
                if (fieldIndex > 0) {
                    inputsRef.current[fieldIndex - 1].current?.focus()
                }
            }
        }
        return (
            <InputItem className={`${error ? "error" : ""} ${className}`}>
                <NameBox>
                    {fieldKeys.map((field, index) => (
                        <BaseInputs
                            key={field}
                            ref={inputsRef.current[index]}
                            type="text"
                            style={style}
                            maxLength={30}
                            value={(value as NameFields)[field] || ""}
                            onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                                handleChange(field, e.target.value)
                            }
                            onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) =>
                                handleKeyDown(e, index)
                            }
                            placeholder={
                                field === "firstName"
                                    ? "First Name"
                                    : field === "middleName"
                                      ? "Middle (optional)"
                                      : "Last Name"
                            }
                        />
                    ))}
                </NameBox>
                {error && (
                    <VerifyMessage>
                        <em>
                            <Svg src={"components/form_item/public_fail_icon.svg"} />
                        </em>
                        {error?.message as string}
                    </VerifyMessage>
                )}
            </InputItem>
        )
    },
)

export default InputName

const InputItem = styled.div`
    position: relative;
    display: flex;
    justify-content: center;
    &.error p {
        display: block;
    }

    &.error input {
        border-color: #fb2d60;
        //background-color: #fee0e7;
    }

    &.error label {
        color: #fb2d60;
    }
`

const NameBox = styled.div`
    display: flex;
    gap: 10rem;
    position: relative;
    &::after,
    &::before {
        content: "";
        position: absolute;
        left: 98rem;
        top: 15rem;
        right: auto;
        height: 0;
        width: 4rem;
        border: 1px solid #d5d5d8;
    }
    &::after {
        right: 98rem;
        left: auto;
    }
`

const BaseInputs = styled(BaseInput)`
    box-sizing: border-box;
    outline: none;
    border: none;
    border-bottom: 1px solid #b3b4bc;
    height: 36rem;
    width: 95rem;
    font-family: "Gilroy", sans-serif;
    font-size: 16rem;
    font-weight: 500;
    padding: 5rem 10rem;
    background-color: #fff;
    color: #9fa7bc;
    line-height: 24rem;
    letter-spacing: 0;
    &::placeholder {
        font-size: 12rem;
    }
`

const VerifyMessage = styled.p`
    display: none;
    position: absolute;
    bottom: -24rem;
    left: 0;
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 12rem;
    line-height: 16rem;
    letter-spacing: 0;
    color: #fb2d60;
    padding-left: 20rem;
    margin: 0;
    & > em {
        position: absolute;
        display: block;
        width: 16rem;
        height: 16rem;
        top: 0;
        left: 0;
        line-height: normal;
        text-align: center;
    }
`
